package com.aaa.dang.modules.system.service.impl;

import com.aaa.dang.common.entity.Employee;
import com.aaa.dang.common.shiro.util.ShiroUtils;
import com.aaa.dang.common.systemlog.annotation.SysLog;
import com.aaa.dang.common.util.ResultModel;
import com.aaa.dang.modules.system.dao.IEmployeeDao;
import com.aaa.dang.modules.system.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Map;
import java.util.UUID;

import static com.aaa.dang.common.systemconst.ISystemConst.FAULT_CODE;
import static com.aaa.dang.common.systemconst.ISystemConst.SUCCESS_CODE;

/**
 * 员工表业务实现
 *
 * @author Dadazhao
 * @date 2018/12/14
 */
@Service
public class EmployeeServiceImpl implements IEmployeeService {

    /**
     * 注入员工dao
     */
    @Autowired
    private IEmployeeDao employeeDao;
    @Autowired
    ResultModel model;

    /**
     * 查询所有员工
     *
     * @param query 查询条件
     * @return 员工列表
     */
    @Override
    public ResultModel getEmployeeAll(Map<String, Object> query) {
        //当page 和 limit 的值不为null或"" 时 进行分页 否则查询所有
        boolean isPaging = (query.get("page") != null && query.get("page") != "") && ((query.get("limit") != null && query.get("limit") != ""));
        if (isPaging) {
            //当前第几页
            int pageNo = Integer.parseInt(query.get("page") + "");
            //一页显示多少行
            int pageSize = Integer.parseInt(query.get("limit") + "");
            //分页插件
            PageHelper.startPage(pageNo, pageSize);
        }
        model.setCode(SUCCESS_CODE);
        model.setMsg("加载成功");
        model.setData(employeeDao.getEmployeeAll(query));
        model.setCount(employeeDao.getEmployeeTotalAll(query));
        return model;
    }

    /**
     * 修改员工的账号状态
     *
     * @param id     员工i的
     * @param status 账号状态
     * @return code 0 成功 1 失败
     */
    @Override
    @SysLog(operateType = SysLog.Type.UPDATE, desc = "修改员工账号状态")
    public ResultModel updateEmployeeStatus(Integer id, Integer status) {
        employeeDao.updateEmployeeStatus(id, status);
        model.setCode(SUCCESS_CODE);
        model.setMsg("变更成功");
        model.setData("");
        return model;
    }

    /**
     * 员工假删除
     *
     * @param id       员工id
     * @param isDelete 0 正常 1删除
     * @return code 0 成功 1 失败
     */
    @Override
    @SysLog(operateType = SysLog.Type.UPDATE, desc = "修改员工删除状态")
    public ResultModel updateEmployeeIsDelete(Integer[] id, int isDelete) {
        int count = employeeDao.updateEmployeeIsDelete(id, isDelete);
        if (count >= 0) {
            model.setCode(SUCCESS_CODE);
            model.setMsg("删除成功");
            model.setData("");
        } else {
            model.setCode(FAULT_CODE);
            model.setMsg("删除失败");
            model.setData("");
        }
        return model;
    }

    /**
     * 1添加员工 获得主键id
     *
     * @param emp   员工实体
     * @param roles 角色id 数组
     * @return code 0 成功 1 失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @SysLog(operateType = SysLog.Type.ADD, desc = "添加新员工")
    public ResultModel addEmployee(Employee emp, Integer[] roles) {
        try {

          /* System.out.println(emp);
            //获得随机值作为盐值
            String uuidStr = UUID.randomUUID().toString();
            //将密码加密
            String encryptionStr = ShiroUtils.getEncryptionStr(emp.getEmpPassword(), uuidStr);
            System.out.println(encryptionStr);
             //添加盐值
            emp.setEmpSalt(uuidStr);
            //将加密的值替换原值
            emp.setEmpPassword(encryptionStr);*/

            if(emp.getEmpPassword()!=null && !"".equals(emp.getEmpPassword())) {
                ShiroUtils.encryption(emp);
            }

            //添加 影响的行数
            int count = employeeDao.addEmployee(emp);
            if (count <= 0) {
                model.setCode(FAULT_CODE);
                model.setMsg("添加失败");
                model.setData("");
                return model;
            }
            //获得用户的主键
            String key = String.valueOf(emp.getId());
            if (roles.length > 1) {
                //将员工id和roles存入员工角色表
                employeeDao.addEmpRoleMapper(key, roles);
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        model.setCode(SUCCESS_CODE);
        model.setMsg("添加成功");
        model.setData("");

        return model;

    }

    /**
     * 通过id获得拥有的角色
     *
     * @param id 员工id
     * @return 角色列表
     */
    @Override
    public ResultModel getHaveRole(Integer id) {
        model.setCode(SUCCESS_CODE);
        model.setData(employeeDao.getHaveRole(id));
        model.setCount(0);
        model.setMsg("查询成功");
        return model;
    }

    /**
     * 修改员工的信息 不包括角色
     *
     * @param emp 员工实体
     * @return code 0 成功 1 失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @SysLog(operateType = SysLog.Type.UPDATE, desc = "修改员工的信息")
    public ResultModel updateEmployee(Employee emp) {
        try {
           /* //获得随机值作为盐值
            String uuidStr = UUID.randomUUID().toString();
            //将密码加密
            String encryptionStr = ShiroUtils.getEncryptionStr(emp.getEmpPassword(), uuidStr);
            //添加盐值
            emp.setEmpSalt(uuidStr);
            //将加密的值替换原值
            emp.setEmpPassword(encryptionStr);*/
            if(emp.getEmpPassword()!=null && !"".equals(emp.getEmpPassword())) {
                ShiroUtils.encryption(emp);
            }
            //修改员工信息
            employeeDao.updateEmployee(emp);

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        model.setCode(SUCCESS_CODE);
        model.setMsg("修改成功");
        model.setData("");
        return model;
    }

    /**
     * 修改员工信息&拥有角色信息
     *
     * @param emp 员工实体
     * @param roles 角色信息
     * @return code 0 成功 1 失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @SysLog(operateType = SysLog.Type.UPDATE, desc = "修改员工的信息&拥有的角色信息")
    public ResultModel updateEmployee(Employee emp, Integer[] roles) {
        try {

           /* //获得随机值作为盐值
            String uuidStr = UUID.randomUUID().toString();
            //添加盐值
            emp.setEmpSalt(uuidStr);
            //得到加密的字符串
            String encryptionStr = ShiroUtils.getEncryptionStr(emp.getEmpPassword(), uuidStr);
            //将加密的值替换原值
            emp.setEmpPassword(encryptionStr);*/
            if(emp.getEmpPassword()!=null && !"".equals(emp.getEmpPassword())) {
                ShiroUtils.encryption(emp);
            }
            //修改员工信息
            employeeDao.updateEmployee(emp);



            //删除已拥有的角色
            employeeDao.deleteHaveRole(emp.getId());
            //前端checkbox由于不选中不发送参数，所以发送了个无效的数据，第一个值为无效的
            if (roles.length > 1) {
                //将员工id和roles存入员工角色表
                employeeDao.addEmpRoleMapper(String.valueOf(emp.getId()), roles);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        model.setCode(SUCCESS_CODE);
        model.setMsg("修改成功");
        model.setData("");
        return model;
    }

    /**
     * 通过登录名获得员工信息
     *
     * @param username 登录名
     * @return 员工信息
     */
    @Override
    public Employee getEmployeeByName(String username) {
        return employeeDao.getEmployeeByName(username);
    }

    /**
     * 登录名唯一性校验
     *
     * @param emp 员工实体
     * @return 存在 0  不存在 1
     */
    @Override
    public ResultModel isExistLoginName(Employee emp) {
        int count = employeeDao.isExistLoginName(emp);
        if (count > 0) {
            model.setCode(SUCCESS_CODE);
            model.setMsg("已存在");
            model.setData("");
            return model;
        } else {
            model.setCode(FAULT_CODE);
            model.setMsg("不存在");
            model.setData("");
            return model;
        }
    }

    /**
     * 通过id删除员工
     *
     * @param id 员工id
     * @return code 0成功 1失败
     */
    @Override
    @SysLog(operateType = SysLog.Type.DELETE, desc = "删除员工")
    public ResultModel deleteEmployeeById(Integer[] id) {
        try {
        employeeDao.deleteEmployeeRoleById(id);
        int count = employeeDao.deleteEmployeeById(id);
            if (count > 0) {
                model.setCode(SUCCESS_CODE);
                model.setMsg("删除成功");
                model.setData("");
                return model;
            }
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        model.setCode(FAULT_CODE);
        model.setMsg("删除失败");
        model.setData("");
        return model;
    }

}
